# -*- encoding: utf-8 -*-
import logging
from django.conf import settings
from offline_calc.handler import OfflineCalculationHandler
from common.mf_pay.mf_pay_handler import create_mf_pay_info
from event_rule.mf_pay.pay_event_rule import rule_config
from common.const import IntervalType, INTERVAL_TYPE_MAPPER

_LOGGER = logging.getLogger(__name__)


class Command(OfflineCalculationHandler):
    def __init__(self):
        super(Command, self).__init__()
        self.index_list = settings.MF_PAY_INDEX
        self.event_config = rule_config.CONFIG

    def add_arguments(self, parser):
        super(Command, self).add_arguments(parser)

    def handle(self, **kwargs):
        super(Command, self).handle(**kwargs)
        merchant = kwargs['merchant']
        self.index_list = self.index_list if not merchant else [index for index in self.index_list if index == merchant]
        self.event_config = {event_name: rule for event_name, rule in self.event_config.items()
                             if not rule.get('real_time_report', False)}
        for index in self.index_list:
            for event_name, config in self.event_config.items():
                interval_type_list = config.get('interval_type_list', [])
                for interval_type_value in interval_type_list:
                    window_list = self.get_window_interval(interval_type_value, config.get('day_to_calc', [0]))
                    for window in window_list:
                        interval_type = INTERVAL_TYPE_MAPPER[interval_type_value]
                        if not isinstance(interval_type, IntervalType):
                            continue
                        print(interval_type, window)
                        self.pool.apipe(self.start_execution, create_mf_pay_info, interval_type, event_name, self.base_time,
                                        index, window,
                                        dict(interval_type=interval_type, base_time=self.base_time, last_window=window,
                                             event_name=event_name, event_rule=config, index=index))
            self.pool.close()
            self.pool.join()
